package com.konsung.ui.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.konsung.bean.CheckData;
import com.konsung.bean.MeasureDataBean;
import com.konsung.healthfile.R;
import com.konsung.network.UploadData;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.ReportListActivity;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.ClickUtils;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 类功能：体检报告列表适配器
 * @author xiangshicheng
 */

public class MeasureReportListAdapter extends BaseAdapter {

    private final Context context;
    private List<MeasureDataBean> measureDataBeans = null; //每页显示的数据
    private LayoutInflater layoutInflater = null;
    private boolean isCheckAll = false; //是否全选 ,默认不全选
    private boolean isOpreateAllSelectBtn = false; //标识是否点击了全选按钮，不管是选中还是未选中，只要点击了则为true

    /**
     * 构造器
     * @param context 上下文
     * @param measureDataBeans 文本数据集
     */
    public MeasureReportListAdapter(Context context, List<MeasureDataBean> measureDataBeans) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        this.measureDataBeans = measureDataBeans;
    }

    @Override
    public int getCount() {
        if (measureDataBeans != null) {
            return measureDataBeans.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return measureDataBeans.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.item_measure_report_list, null);
            ButterKnife.bind(viewHolder, convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        final MeasureDataBean measureDataBean = measureDataBeans.get(position);
        viewHolder.tvSerial.setText(position + 1 + "");
        viewHolder.tvMeasureTime.setText(UiUtils.getDateFormat(UiUtils.DateState.LONG)
                .format(measureDataBean.getMeasureTime()));
        boolean isUpload = measureDataBean.getUploadFlag();
        if (isUpload) {
            viewHolder.tvUploadState.setText(UiUtils.getString(R.string.have_already_uploaded));
            viewHolder.ivOtherOperate.setImageResource(R.mipmap.ic_uploaded);
            viewHolder.ivOtherOperate.setEnabled(false);
        } else {
            viewHolder.tvUploadState.setText(UiUtils.getString(R.string.haven_uploaded));
            viewHolder.ivOtherOperate.setImageResource(R.mipmap.ic_upload);
            viewHolder.ivOtherOperate.setEnabled(true);
        }
        String uuid = measureDataBean.getUuid();
        if (isCheckAll) {
            viewHolder.cbChoose.setChecked(isCheckAll);
        } else {
            List<String> uuidList = getUuidByMeasureDataBean(((ReportListActivity) context)
                    .getSelectNeedDeleteList());
            if (uuidList.contains(uuid)) {
                viewHolder.cbChoose.setChecked(true);
            } else {
                viewHolder.cbChoose.setChecked(false);
            }
        }
        viewHolder.cbChoose.setTag(position);
        viewHolder.cbChoose.setOnCheckedChangeListener(new CompoundButton
                .OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                Log.e("xsc_isOp", "" + isOpreateAllSelectBtn);
                Log.e("xsc_position", position + "-" + measureDataBeans.size());
                if (isOpreateAllSelectBtn) {
                    //操作了全选按钮的情况下不走该回调
                } else {
                    ((ReportListActivity) context).showViewData(measureDataBean, isChecked);
                }
            }
        });
        int mPosition = (int) viewHolder.cbChoose.getTag();
        Log.e("xsc_mposition", "" + mPosition);
        if (mPosition == (measureDataBeans.size() - 1)) {
            isOpreateAllSelectBtn = false;
        }
        viewHolder.ivOtherOperate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //数据上传
                if (!ClickUtils.isFastClickTwo()) {
                    return;
                }
                if (UiUtils.isConnectNetWork(context)) {
                    UiUtils.postLongThread(new Runnable() {
                        @Override
                        public void run() {
                            CheckData checkData = ProviderReader.getCheckData(context);
                            if (checkData == null) {
                                ToastUtils.showShortToastSafe(UiUtils
                                        .getString(R.string.user_not_upload));
                                return;
                            }
                            UiUtils.showProgress(context, UiUtils.getString(R.string.now_upload));
                            UploadData uploadData = new UploadData(context);
                            final boolean isFile = uploadData.uploadMeasureDataMore(measureDataBean,
                                    ((ReportListActivity) context).getCurrentPatient(), checkData
                                    , true);
                            UiUtils.post(new Runnable() {
                                @Override
                                public void run() {
                                    //查询到没有健康档案就不进行上传了
                                    if (!isFile) {
                                        ToastUtils.showShortToastSafe(UiUtils.getString(R
                                                .string.no_file_please_upload));
                                    } else {
                                        if (measureDataBean.getUploadFlag()) {
                                            //上传成功
                                            viewHolder.ivOtherOperate
                                                    .setImageResource(R.mipmap.ic_uploaded);
                                            viewHolder.ivOtherOperate.setEnabled(false);
                                            viewHolder.tvUploadState.setText(UiUtils
                                                    .getString(R.string.have_already_uploaded));
                                            ToastUtils.showShortToast(R.string.upload_success);
                                            //操作数据上传后就通知首页刷新列表显示
                                            BroadcastUtils.sendAddPatientSuccess();
                                            BroadcastUtils.sendReplacePatientForAll();
                                        } else {
                                            //上传失败
                                            viewHolder.tvUploadState.setText(UiUtils
                                                    .getString(R.string.haven_uploaded));
                                            ToastUtils.showShortToast(R.string.upload_failure);
                                        }
                                    }
                                    UiUtils.hideProgress();
                                }
                            });
                        }
                    });
                } else {
                    ToastUtils.showShortToastSafe(R.string.no_net);
                }
            }
        });
        return convertView;
    }

    /**
     * 视图容器
     */
    class ViewHolder {
        @BindView(R.id.tv_serial)
        TextView tvSerial; //序号
        @BindView(R.id.tv_report_item_measure_time)
        TextView tvMeasureTime; //测量时间
        @BindView(R.id.tv_report_item_upload_state)
        TextView tvUploadState; //上传状态
        @BindView(R.id.iv_other_operate)
        ImageView ivOtherOperate; //上传按钮
        @BindView(R.id.cbx_select)
        CheckBox cbChoose; //勾选框
    }

    /**
     * 设置数据
     * @param list 数据
     */
    public void setDatas(List<MeasureDataBean> list) {
        measureDataBeans = list;
        notifyDataSetChanged();
    }

    /**
     * 设置是否全选
     * @param checkAll 是否全选标记
     */
    public void setCheckAll(boolean checkAll) {
        this.isCheckAll = checkAll;
        isOpreateAllSelectBtn = true;
        notifyDataSetChanged();
    }

    /**
     * 设置全选按钮操作状态值
     * @param state 值
     */
    public void setValue(boolean state) {
        isOpreateAllSelectBtn = state;
    }

    /**
     * 获取测量数据UUID集合
     * @param list UUID数据集合
     * @return UUID集合
     */
    private List<String> getUuidByMeasureDataBean(List<MeasureDataBean> list) {
        List<String> stringList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (MeasureDataBean measureDataBean : list) {
                stringList.add(measureDataBean.getUuid());
            }
        }
        return stringList;
    }
}
